import express from 'express';
import { body, param, validationResult } from 'express-validator';
import { executeQuery, getOne, transaction } from '../config/database.js';
import { authenticateToken, requireAdmin } from '../middleware/auth.js';
import { emitStudentStatusUpdate, emitAfterSchoolUpdate } from '../utils/socketService.js';

const router = express.Router();

// 中间件：验证课后老师权限
const requireAfterSchoolTeacher = async (req, res, next) => {
  if (req.user.role === 'after_school_teacher' || req.user.role === 'admin') {
    next();
  } else {
    return res.status(403).json({
      success: false,
      message: '权限不足，需要课后老师或管理员权限'
    });
  }
};

// 获取所有托班班级
router.get('/classes', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 10;
    const offset = (pageNum - 1) * limitNum;

    // 根据用户角色决定查询范围
    let sql = `
      SELECT 
        ac.id, ac.name, ac.description, 
        ac.teacher_id, u.name as teacher_name,
        ac.created_at, ac.updated_at
      FROM after_school_classes ac
      JOIN users u ON ac.teacher_id = u.id
    `;
    
    let countSql = 'SELECT COUNT(*) as total FROM after_school_classes';
    let params = [];
    let countParams = [];
    
    // 如果是课后老师，只能看到自己负责的班级
    if (req.user.role === 'after_school_teacher') {
      sql += ' WHERE ac.teacher_id = ?';
      countSql += ' WHERE teacher_id = ?';
      params.push(req.user.id);
      countParams.push(req.user.id);
    }

    sql += ` ORDER BY ac.name LIMIT ${limitNum} OFFSET ${offset}`;
    
    const classes = await executeQuery(sql, params);
    const totalResult = await getOne(countSql, countParams);

    res.json({
      success: true,
      data: {
        classes,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total: totalResult.total,
          pages: Math.ceil(totalResult.total / limitNum)
        }
      }
    });

  } catch (error) {
    console.error('获取托班班级列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 创建托班班级（仅管理员）
router.post('/classes', [
  authenticateToken,
  requireAdmin,
  body('name').trim().notEmpty().withMessage('班级名称不能为空'),
  body('teacher_id').isInt().withMessage('教师ID必须是整数'),
  body('description').optional().trim(),
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { name, teacher_id, description } = req.body;

    // 验证教师是否存在且是课后老师
    const teacher = await getOne(
      'SELECT id FROM users WHERE id = ? AND role = "after_school_teacher"',
      [teacher_id]
    );

    if (!teacher) {
      return res.status(400).json({
        success: false,
        message: '指定的课后老师不存在'
      });
    }

    // 创建托班班级
    const result = await executeQuery(`
      INSERT INTO after_school_classes (name, teacher_id, description) 
      VALUES (?, ?, ?)
    `, [name, teacher_id, description || null]);

    res.status(201).json({
      success: true,
      message: '托班班级创建成功',
      data: {
        id: result.insertId,
        name,
        teacher_id,
        description
      }
    });

  } catch (error) {
    console.error('创建托班班级错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取单个托班班级详情
router.get('/classes/:id', [
  authenticateToken,
  param('id').isInt().withMessage('班级ID必须是整数')
], async (req, res) => {
  try {
    const classId = parseInt(req.params.id);
    
    // 获取班级信息
    const classInfo = await getOne(`
      SELECT 
        ac.id, ac.name, ac.description, 
        ac.teacher_id, u.name as teacher_name,
        ac.created_at, ac.updated_at
      FROM after_school_classes ac
      JOIN users u ON ac.teacher_id = u.id
      WHERE ac.id = ?
    `, [classId]);

    if (!classInfo) {
      return res.status(404).json({
        success: false,
        message: '托班班级不存在'
      });
    }

    // 如果是课后老师，只能查看自己负责的班级
    if (req.user.role === 'after_school_teacher' && classInfo.teacher_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '权限不足，只能查看自己负责的班级'
      });
    }

    res.json({
      success: true,
      data: classInfo
    });

  } catch (error) {
    console.error('获取托班班级详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 更新托班班级信息（仅管理员）
router.put('/classes/:id', [
  authenticateToken,
  requireAdmin,
  param('id').isInt().withMessage('班级ID必须是整数'),
  body('name').optional().trim().notEmpty().withMessage('班级名称不能为空'),
  body('teacher_id').optional().isInt().withMessage('教师ID必须是整数'),
  body('description').optional().trim(),
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const classId = parseInt(req.params.id);
    const { name, teacher_id, description } = req.body;

    // 检查班级是否存在
    const classExists = await getOne(
      'SELECT id FROM after_school_classes WHERE id = ?',
      [classId]
    );

    if (!classExists) {
      return res.status(404).json({
        success: false,
        message: '托班班级不存在'
      });
    }

    // 如果提供了teacher_id，验证教师是否存在且是课后老师
    if (teacher_id) {
      const teacher = await getOne(
        'SELECT id FROM users WHERE id = ? AND role = "after_school_teacher"',
        [teacher_id]
      );

      if (!teacher) {
        return res.status(400).json({
          success: false,
          message: '指定的课后老师不存在'
        });
      }
    }

    // 构建更新SQL
    let updateFields = [];
    let updateParams = [];

    if (name !== undefined) {
      updateFields.push('name = ?');
      updateParams.push(name);
    }

    if (teacher_id !== undefined) {
      updateFields.push('teacher_id = ?');
      updateParams.push(teacher_id);
    }

    if (description !== undefined) {
      updateFields.push('description = ?');
      updateParams.push(description);
    }

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段'
      });
    }

    // 添加班级ID到参数数组
    updateParams.push(classId);

    // 执行更新
    await executeQuery(
      `UPDATE after_school_classes SET ${updateFields.join(', ')} WHERE id = ?`,
      updateParams
    );

    res.json({
      success: true,
      message: '托班班级更新成功'
    });

  } catch (error) {
    console.error('更新托班班级错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 删除托班班级（仅管理员）
router.delete('/classes/:id', [
  authenticateToken,
  requireAdmin,
  param('id').isInt().withMessage('班级ID必须是整数')
], async (req, res) => {
  try {
    const classId = parseInt(req.params.id);

    // 检查班级是否存在
    const classExists = await getOne(
      'SELECT id FROM after_school_classes WHERE id = ?',
      [classId]
    );

    if (!classExists) {
      return res.status(404).json({
        success: false,
        message: '托班班级不存在'
      });
    }

    // 删除班级
    await executeQuery('DELETE FROM after_school_classes WHERE id = ?', [classId]);

    res.json({
      success: true,
      message: '托班班级删除成功'
    });

  } catch (error) {
    console.error('删除托班班级错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取课后老师列表
router.get('/teachers', authenticateToken, async (req, res) => {
  try {
    const teachers = await executeQuery(`
      SELECT 
        u.id, u.username, u.name, u.phone,
        COALESCE(GROUP_CONCAT(ac.name SEPARATOR ', '), '') as classes
      FROM users u
      LEFT JOIN after_school_classes ac ON u.id = ac.teacher_id
      WHERE u.role = 'after_school_teacher'
      GROUP BY u.id, u.username, u.name, u.phone
      ORDER BY u.name
    `);

    res.json({
      success: true,
      data: teachers
    });

  } catch (error) {
    console.error('获取课后老师列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 学生进入托班（课后老师）
router.post('/check-in', [
  authenticateToken,
  requireAfterSchoolTeacher,
  body('student_id').isInt().withMessage('学生ID必须是整数'),
  body('attendance_record_id').isInt().withMessage('考勤记录ID必须是整数'),
  body('after_school_class_id').isInt().withMessage('托班班级ID必须是整数'),
  body('notes').optional().trim(),
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { student_id, attendance_record_id, after_school_class_id, notes } = req.body;
    const teacher_id = req.user.id;

    // 验证学生是否存在
    const student = await getOne('SELECT id, name FROM students WHERE id = ?', [student_id]);
    if (!student) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    // 验证考勤记录是否存在
    const record = await getOne('SELECT id, departure_status, after_school_check_out_time FROM attendance_records WHERE id = ?', [attendance_record_id]);
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '考勤记录不存在'
      });
    }

    // 验证托班班级是否存在
    const afterSchoolClass = await getOne('SELECT id, teacher_id FROM after_school_classes WHERE id = ?', [after_school_class_id]);
    if (!afterSchoolClass) {
      return res.status(404).json({
        success: false,
        message: '托班班级不存在'
      });
    }

    // 验证当前用户是否是该托班的负责老师（管理员除外）
    if (req.user.role !== 'admin' && afterSchoolClass.teacher_id !== teacher_id) {
      return res.status(403).json({
        success: false,
        message: '权限不足，只能为自己负责的托班签到学生'
      });
    }

    // 检查学生是否已经离班（通过检查after_school_check_out_time字段）
    if (record.after_school_check_out_time) {
      return res.status(400).json({
        success: false,
        message: '学生已经离班，不能再次签到'
      });
    }

    // 开始事务
    await transaction(async (connection) => {
      // 更新考勤记录，添加课后托班信息
      await connection.query(
        `UPDATE attendance_records 
         SET departure_status = "class_left", 
             after_school_class_id = ?, 
             after_school_check_in_time = NOW(), 
             after_school_check_in_teacher_id = ?, 
             notes = ? 
         WHERE id = ?`,
        [after_school_class_id, teacher_id, notes || null, attendance_record_id]
      );
    });
    
    // 发送WebSocket通知
    emitStudentStatusUpdate({
      studentId: student_id,
      classId: student.class_id,
      updateType: 'after_school_check_in',
      status: 'class_left',
      timestamp: new Date(),
      notes: notes || null
    });
    
    // 发送课后托班状态更新通知
    emitAfterSchoolUpdate({
      studentId: student_id,
      studentName: student.name,
      attendanceRecordId: attendance_record_id,
      afterSchoolClassId: after_school_class_id,
      action: 'check_in',
      timestamp: new Date(),
      notes: notes || null
    });

    res.json({
      success: true,
      message: `学生 ${student.name} 已成功进入托班`,
      data: {
        student_id,
        student_name: student.name,
        after_school_class_id
      }
    });

  } catch (error) {
    console.error('学生进入托班错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 学生离开托班（课后老师）
router.post('/check-out', [
  authenticateToken,
  requireAfterSchoolTeacher,
  body('student_id').isInt().withMessage('学生ID必须是整数'),
  body('attendance_record_id').isInt().withMessage('考勤记录ID必须是整数'),
  body('notes').optional().trim(),
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { student_id, attendance_record_id, notes } = req.body;
    const teacher_id = req.user.id;

    // 验证学生是否存在
    const student = await getOne('SELECT id, name FROM students WHERE id = ?', [student_id]);
    if (!student) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    // 验证考勤记录是否存在并检查课后托班状态
    const record = await getOne(`
      SELECT ar.id, ar.after_school_class_id, ar.after_school_check_in_time, ar.after_school_check_out_time, asc.teacher_id
      FROM attendance_records ar
      LEFT JOIN after_school_classes asc ON ar.after_school_class_id = asc.id
      WHERE ar.id = ?
    `, [attendance_record_id]);
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '考勤记录不存在'
      });
    }

    // 检查学生是否在托班中
    if (!record.after_school_class_id || !record.after_school_check_in_time) {
      return res.status(404).json({
        success: false,
        message: '学生未进入托班'
      });
    }

    // 验证当前用户是否是该托班的负责老师（管理员除外）
    if (req.user.role !== 'admin' && record.teacher_id !== teacher_id) {
      return res.status(403).json({
        success: false,
        message: '权限不足，只能为自己负责的托班签退学生'
      });
    }

    // 如果学生已经离班，则不能再次签退
    if (record.after_school_check_out_time) {
      return res.status(400).json({
        success: false,
        message: '学生已经离班'
      });
    }

    // 开始事务
    await transaction(async (connection) => {
      // 更新考勤记录，添加课后托班离班信息
      await connection.query(`
        UPDATE attendance_records 
        SET departure_status = "class_left", after_school_check_out_time = NOW() 
        WHERE id = ?
      `, [attendance_record_id]);
    });
    
    // 发送WebSocket通知
    emitStudentStatusUpdate({
      studentId: student_id,
      classId: student.class_id,
      updateType: 'after_school_check_out',
      status: 'class_left',
      timestamp: new Date(),
      notes: notes || null
    });
    
    // 发送课后托班状态更新通知
    emitAfterSchoolUpdate({
      studentId: student_id,
      studentName: student.name,
      attendanceRecordId: attendance_record_id,
      afterSchoolClassId: record.after_school_class_id,
      action: 'check_out',
      timestamp: new Date(),
      notes: notes || null
    });

    res.json({
      success: true,
      message: `学生 ${student.name} 已成功离开托班`,
      data: {
        student_id,
        student_name: student.name
      }
    });

  } catch (error) {
    console.error('学生离开托班错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取托班学生列表
router.get('/students', [
  authenticateToken,
  requireAfterSchoolTeacher
], async (req, res) => {
  try {
    const { class_id, date, status } = req.query;
    const teacher_id = req.user.id;
    
    // 构建日期条件
    const today = date ? new Date(date) : new Date();
    const dateStr = today.toISOString().split('T')[0];
    
    // 构建查询
    let sql = `
      SELECT 
        s.id as student_id, s.name as student_name, s.student_no,
        c.id as class_id, c.name as class_name,
        ar.id as attendance_record_id, ar.arrival_status, ar.departure_status,
        ar.after_school_class_id, 
        CASE 
          WHEN ar.after_school_check_in_time IS NOT NULL AND ar.after_school_check_out_time IS NULL THEN 'checked_in'
          WHEN ar.after_school_check_out_time IS NOT NULL THEN 'checked_out'
          ELSE 'pending'
        END AS check_in_status,
        ar.after_school_check_in_time as check_in_time, 
        ar.after_school_check_out_time as check_out_time,
        asc.id as after_school_class_id, asc.name as after_school_class_name,
        ar.notes as notes
      FROM students s
      JOIN classes c ON s.class_id = c.id
      JOIN attendance_records ar ON s.id = ar.student_id AND DATE(ar.attendance_date) = ?
      LEFT JOIN after_school_classes asc ON ar.after_school_class_id = asc.id
    `;
    
    let params = [dateStr];
    
    // 添加班级筛选
    if (class_id) {
      sql += ' AND asc.id = ?';
      params.push(class_id);
    } else if (req.user.role !== 'admin') {
      // 非管理员只能看到自己负责的托班学生
      sql += ' AND asc.teacher_id = ?';
      params.push(teacher_id);
    }
    
    // 添加状态筛选
    if (status === 'checked_in') {
      sql += ' AND ar.after_school_check_in_time IS NOT NULL AND ar.after_school_check_out_time IS NULL';
    } else if (status === 'checked_out') {
      sql += ' AND ar.after_school_check_out_time IS NOT NULL';
    } else if (status === 'pending') {
      sql += ' AND ar.after_school_class_id IS NULL';
    }
    
    // 排序
    sql += ' ORDER BY asc.name, s.name';
    
    const students = await executeQuery(sql, params);
    
    res.json({
      success: true,
      data: students
    });

  } catch (error) {
    console.error('获取托班学生列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

export default router;